package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"math"
	"os"
	"time"
)

func LoggerMiddleware()gin.HandlerFunc{

	logPath := "log/"
	linkName := "last_log.log"

	//write log to file
	//srcFile,err := os.OpenFile("log/log.log",os.O_RDWR|os.O_CREATE,775)
	//if err != nil {
	//	fmt.Println("err", err)
	//}

	logger := logrus.New()
	//设置日志级别
	logger.SetLevel(logrus.DebugLevel)
	//设置输出文件
	//logger.Out = srcFile


	// 设置 rotatelogs
	logWriter, _ := rotatelogs.New(
		// 分割后的文件名称
		logPath + "%Y-%m-%d.log",

		// 生成软链，指向最新日志文件
		rotatelogs.WithLinkName(linkName),

		// 设置最大保存时间(7天)
		rotatelogs.WithMaxAge(7*24*time.Hour),

		// 设置日志切割时间间隔(1天)
		rotatelogs.WithRotationTime(24*time.Hour),
	)

	writeMap := lfshook.WriterMap{
		logrus.InfoLevel:  logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
		logrus.WarnLevel:  logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.PanicLevel: logWriter,
	}

	logger.AddHook(lfshook.NewHook(writeMap, &logrus.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	}))

	return func(c *gin.Context) {
		startTime := time.Now()
		c.Next()
		stopTime := time.Since(startTime)

		spendTime := fmt.Sprintf("%d ms",int(math.Ceil(float64(stopTime.Milliseconds()))))
		hostName,err := os.Hostname()
		if err!=nil{
			hostName = "unknown"
		}
		statusCode := c.Writer.Status()
		userAgent := c.Request.UserAgent()
		clientIp := c.ClientIP()
		method := c.Request.Method
		path := c.Request.RequestURI
		dataSize := c.Writer.Size()

		//日志格式
		entry := logger.WithFields(logrus.Fields{
			"spendTime":spendTime,
			"HostName":hostName,
			"statusCode":statusCode,
			"Agent":userAgent,
			"IP":clientIp,
			"method":method,
			"path":path,
			"dataSize":dataSize,
		})

		if len(c.Errors) > 0{
			entry.Error(gin.ErrorTypePrivate)
		}else if statusCode >= 500{
			entry.Error("error")
		}else if statusCode >= 400{
			entry.Warn("warn")
		}else {
			entry.Info("info")
		}
	}
}